package yxy.game.pm2.active.module;

import org.joda.time.DateTime;
import yxy.apple.util.redisson.RedisException;
import yxy.cherry.data.bean.actlimitpackage;
import yxy.game.pm2.active.module.actdata.ActDataCenter;
import yxy.game.pm2.active.module.lockorder.LockOrderInfo;
import yxy.game.pm2.active.module.subordinateclass.LimitGiftPackage;
import yxy.game.pm2.bean.PlayerBean;
import yxy.game.pm2.bean.db.dao.MySQLCacheDAO;
import yxy.game.pm2.bean.module.PlayerModule;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

/**
 * 限时礼包
 *
 * @author Dell
 */
public class ActiveModule_限时礼包_Person extends PlayerModule {

    //bean -------------------------------
    public static final int acttype = 11;

    private int days;    //第几天
    private ArrayList<LimitGiftPackage> newlgps = new ArrayList<LimitGiftPackage>();    //礼包信息

    public int getDays() {
        return days;
    }

    public void setDays(int days) {
        this.days = days;
    }

    public ArrayList<LimitGiftPackage> getNewlgps() {
        return newlgps;
    }

    public void setNewlgps(ArrayList<LimitGiftPackage> newlgps) {
        this.newlgps = newlgps;
    }

    //func ---------------------------------

    private static ActiveModule_限时礼包_Person create(String playerCode) {
        PlayerBean pb = PlayerBean.get(playerCode);
        if (pb == null) {
            return null;
        }

        ActiveModule_限时礼包_Area areaactiveinfo = ActiveModule_限时礼包_Area.get(pb.getServerId());
        if (areaactiveinfo == null) {
            return null;
        }

        int days = areaactiveinfo.getDay();

        ActiveModule_限时礼包_Person am = new ActiveModule_限时礼包_Person();
        am.setDays(days);
        am.setPlayerCode(playerCode);

        Map<String, actlimitpackage> alpmap = ActDataCenter.getAllData(actlimitpackage.class, playerCode);
        for (actlimitpackage alp : alpmap.values()) {
            if (alp.getDay() != days) {
                continue;
            }

            LimitGiftPackage lgp = new LimitGiftPackage();
            lgp.setId(alp.getId());
            lgp.setGoodsid(alp.getPurchasever());
            lgp.setBuy(0);
            lgp.setLimit(alp.getLimit());
            am.getNewlgps().add(lgp);
        }

        am.set();
        return am;
    }

    public int canBuy(int goodsid) {
        for (LimitGiftPackage lgp : getNewlgps()) {
            if (lgp.getGoodsid() == goodsid) {
                int locknum = lgp.getLockorder().size();
                int buynum = lgp.getBuy();
                if (locknum + buynum < lgp.getLimit()) {
                    return DrawStatus.canget.getStatus();
                }
            }
        }
        return DrawStatus.cannotget.getStatus();
    }

    /**
     * 处理购买完成
     *
     * @param goodsid
     * @param myorderid
     */
    public void handlebuy(int goodsid, String myorderid) {
        for (LimitGiftPackage lgp : getNewlgps()) {
            if (lgp.getGoodsid() == goodsid) {
                //解锁单
                lgp.getLockorder().remove(myorderid);
                //增加购买次数
                int buynum = lgp.getBuy();
                buynum++;
                lgp.setBuy(buynum);
                set();
            }
        }
    }

    /**
     * 锁单
     *
     * @param goodsid
     * @param myorderid
     */
    public void lockorder(int goodsid, String myorderid) {
        for (LimitGiftPackage lgp : getNewlgps()) {
            if (lgp.getGoodsid() == goodsid) {
                lgp.getLockorder().put(myorderid, DateTime.now());
                set();
            }
        }
    }

//	public static final int canget = 1;
//	public static final int hadget = 2;
//	public static final int cannotget = 3;

    // redis ---------------------------------------------------

    static private String key(String playerCode) {
        return String.format("PLAYER:%s:ACTIVE:%S", playerCode, acttype);
    }

    public void set() {
        try {
            setv(key(getPlayerCode()), this);
            check();
        } catch (RedisException e) {
            e.printStackTrace();
        }
    }

    static public ActiveModule_限时礼包_Person get(String playerCode, Boolean isNewPlayer) {
        try {
            ActiveModule_限时礼包_Person module = getv(key(playerCode));

            //新用户不需要去查数据库
            if (module == null && !isNewPlayer) {
                module = MySQLCacheDAO.getV(key(playerCode), ActiveModule_限时礼包_Person.class);
                if (module != null) {
                    module.set();
                }//同步到redis
            }

            if (module == null) {
                module = create(playerCode);
            }
            if (module == null) {
                return null;
            }

            module.update();
            module.check();
            return module;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private void update() {
        PlayerBean pb = PlayerBean.get(getPlayerCode());
        if (pb == null) {
            return;
        }

        ActiveModule_限时礼包_Area areaactiveinfo = ActiveModule_限时礼包_Area.get(pb.getServerId());
        if (areaactiveinfo == null) {
            return;
        }

        if (areaactiveinfo.getDay() != getDays()) {
            int days = areaactiveinfo.getDay();
            ArrayList<LimitGiftPackage> newlgps = new ArrayList<LimitGiftPackage>();
            Map<String, actlimitpackage> alpmap = ActDataCenter.getAllData(actlimitpackage.class, getPlayerCode());
            for (actlimitpackage alp : alpmap.values()) {
                if (alp.getDay() != days) {
                    continue;
                }

                LimitGiftPackage lgp = new LimitGiftPackage();
                lgp.setId(alp.getId());
                lgp.setGoodsid(alp.getPurchasever());
                lgp.setBuy(0);
                lgp.setLimit(alp.getLimit());
                newlgps.add(lgp);
            }

            setDays(days);
            setNewlgps(newlgps);
            set();
        }

        //检查锁单
        boolean save = false;
        for (LimitGiftPackage lgp : getNewlgps()) {
            ArrayList<String> removekey = new ArrayList<String>();
            HashMap<String, DateTime> lockinfo = lgp.getLockorder();
            if (lockinfo.size() == 0) {
                continue;
            }

            for (String myorderid : lockinfo.keySet()) {
                DateTime time = lockinfo.get(myorderid);
                if (DateTime.now().getMillis() - time.getMillis() > LockOrderInfo.lockTime()) {
                    removekey.add(myorderid);
                }
            }

            for (String key : removekey) {
                save = true;
                lockinfo.remove(key);
            }
        }

        if (save) {
            set();
        }
    }

    /**
     * 查看是否有可领取奖励 控制红点
     */
    public void check() {
        PlayerBean pb = PlayerBean.get(getPlayerCode());
        if (pb == null) {
            return;
        }

        ActiveModule_限时礼包_Area areaactiveinfo = ActiveModule_限时礼包_Area.get(pb.getServerId());
        if (areaactiveinfo == null) {
            new ActOpenHandle().updateActOpen(getPlayerCode(), acttype, OpenType.关闭);
            return;
        }

        if (areaactiveinfo.running()) {
            if (getNewlgps().size() != 0) {
                new ActOpenHandle().updateActOpen(getPlayerCode(), acttype, OpenType.开启);
                return;
            }
        }
        new ActOpenHandle().updateActOpen(getPlayerCode(), acttype, OpenType.关闭);
    }

    /**
     * 正常情况下不要使用这个方法
     */
    static public Collection<ActiveModule_限时礼包_Person> all() {
        ArrayList<ActiveModule_限时礼包_Person> list = new ArrayList<>();
        try {
            Iterable<String> iterable = redis().client().getKeys().getKeysByPattern(key("*"));
            for (String code : iterable) {
                ActiveModule_限时礼包_Person bean = getv(code);
                if (bean != null) {
                    list.add(bean);
                }
            }
        } catch (RedisException e) {
            e.printStackTrace();
        }
        return list;
    }

    //存储到数据库的方法
    public static void saveToDB(String playerCode) {
        try {
            String key = key(playerCode);
            if (touchBucket(key).isExists()) {
                ActiveModule_限时礼包_Person activeModule_限时礼包_Person = getv(key(playerCode));
                MySQLCacheDAO.setV(key, activeModule_限时礼包_Person);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    //从redis移走数据的操作
    public static void removeAllFromRedis(String playerCode) {
        try {
            touchBucket(key(playerCode)).delete();
        } catch (RedisException e) {
            e.printStackTrace();
        }
    }
    // lock==========================================================================

    @Override
    public String lockKey() {
        return String.format("lock:%s", key(getPlayerCode()));
    }

}
